import './index.less'
import { useEffect, forwardRef, useImperativeHandle } from 'react'

import { useSearchParams } from 'react-router-dom'
import { Form, Button, Input, Select, Radio } from 'antd'

const AForm = forwardRef((props, ref) => {
  const { title = '', sectionlist = [], onSubmit, detail, type } = props
  const [form] = Form.useForm()
  const [searchParams] = useSearchParams() // 获取查询参数
  const id = searchParams.get('id')
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields()
      onSubmit?.(values)
    } catch (error) {
      console.log('表单验证失败:', error)
    }
  }

  useEffect(() => {
    if (!detail || !id) return
    if (Object.keys(detail).length > 0) {
      form.setFieldsValue(detail)
    }
  }, [detail, id])

  /** 获取详情状态下，各字段的·值 */
  const getDetailValue = (section) => {
    if (!detail) return ''
    if (section?.options?.length > 0) {
      return section?.options?.find(
        (item) => item?.value === detail?.[section?.name]
      )?.label
    } else {
      return detail?.[section?.name]
    }
  }

  useImperativeHandle(ref, () => ({
    async getFormValue() {
      const values = await form.validateFields()
      return values
    },
  }))

  return (
    <div className="form-container">
      {type !== 'detail' ? (
        <>
          <div className="form-title">
            <div className="form-title-text">{title}</div>
            <Button type="primary" variant="solid" onClick={handleSubmit}>
              保存
            </Button>
          </div>
          {sectionlist?.length > 0 && (
            <Form
              form={form}
              labelCol={{ flex: '120px' }}
              wrapperCol={{ flex: 1 }}
              initialValues={detail}
            >
              {sectionlist?.map((section) => {
                const { type = 'input', name, label, rules } = section || {}
                return (
                  <Form.Item
                    label={label}
                    name={name}
                    rules={rules}
                    className="form-item-container"
                    key={name}
                    labelAlign="right"
                    initialValue={
                      type === 'radio'
                        ? section?.defaultValue ||
                          section?.options?.[0]?.value ||
                          ''
                        : type === 'select'
                        ? undefined
                        : ''
                    }
                  >
                    {type === 'input' && (
                      <Input
                        className="filter-input"
                        showCount={!!section?.maxLength}
                        placeholder={section?.placeholder || '请输入'}
                        size={section?.size || 'large'}
                        maxLength={section?.maxLength || Infinity}
                      />
                    )}
                    {type === 'textArea' && (
                      <Input.TextArea
                        showCount={!!section?.maxLength}
                        placeholder={section?.placeholder || '请输入'}
                        size={section?.size || 'large'}
                        maxLength={section?.maxLength || Infinity}
                        style={{
                          height: 140,
                          resize: 'none',
                        }}
                      />
                    )}
                    {type === 'select' && (
                      <Select
                        className="select-input"
                        options={section?.options || []}
                        defaultValue={
                          section?.defaultValue ||
                          section?.options?.[0]?.value ||
                          (section?.itemProps?.placeholder ? undefined : '')
                        }
                        {...(section?.itemProps || {})}
                        {...(section.itemEvents || {})}
                      />
                    )}

                    {type === 'radio' && (
                      <Radio.Group
                        defaultValue={
                          section?.defaultValue ||
                          section?.options?.[0]?.value ||
                          ''
                        }
                        name="radiogroup"
                        options={section?.options || []}
                        {...(section?.itemProps || {})}
                        {...(section.itemEvents || {})}
                      />
                    )}
                    {type === 'self' && section.selftComponent({ form })}
                  </Form.Item>
                )
              })}
            </Form>
          )}
        </>
      ) : (
        <div className="form-detail-container">
          {sectionlist?.map((section) => {
            return section?.type !== 'self' ? (
              <div className="form-detail-section">
                <div className="form-detail-section-label">
                  {section?.label}：
                </div>
                <div className="form-detail-section-value">
                  {getDetailValue(section)}
                </div>
              </div>
            ) : (
              <div style={{ marginLeft: '-40px' }}>
                {section?.selftComponent({ form })}
              </div>
            )
          })}
        </div>
      )}
    </div>
  )
})
export default AForm
